package com.kjlink.internal.workreport.helper;

import cn.dev33.satoken.stp.StpUtil;
import cn.xuqiudong.common.base.tool.Tools;
import com.kjlink.internal.workreport.base.constant.CommonConstant;
import com.kjlink.internal.workreport.user.model.User;
import com.kjlink.internal.workreport.util.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpSession;

/**
 * 描述:
 * session util
 *
 * @author Vic.xu
 * @since 2024-04-30 11:11
 */
public class SessionHelper {

    private static final Logger LOGGER = LoggerFactory.getLogger(SessionHelper.class);

    //把用户信息绑定到当前线程(子线程可继承) 注意清理线程数据
    private static final InheritableThreadLocal INHERITABLE_USER_THREAD_LOCAL = new InheritableThreadLocal();


    /**
     * 把用户信息绑定到 当前线程 INHERITABLE_USER_THREAD_LOCAL
     */
    public static void storeUser2InheritableLocal(User user) {
        INHERITABLE_USER_THREAD_LOCAL.set(user);
    }

    /**
     * 从当前线程INHERITABLE_USER_THREAD_LOCAL 取出用户信息
     */
    public static User getUserFromInheritableLocal() {
        return (User) INHERITABLE_USER_THREAD_LOCAL.get();
    }

    /**
     * 从当前线程INHERITABLE_USER_THREAD_LOCAL clean user info
     */
    public static void cleanUserFromInheritableLocal() {
        INHERITABLE_USER_THREAD_LOCAL.remove();
    }


    /**
     * 保存用户到session
     */
    public static void storeUser(User user) {
        Tools.currentRequest().getSession().setAttribute(CommonConstant.PRINCIPAL, user);
        if (!StpUtil.isLogin()) {
            StpUtil.login(user.getId());
        }
    }

    /**
     * 清除session
     */
    public static void cleanSession() {
        HttpSession httpSession = Tools.currentSession();
        if (httpSession == null) {
            return;
        }
        httpSession.setAttribute(CommonConstant.PRINCIPAL, null);
        httpSession.invalidate();
    }

    /**
     * 当前用户
     *
     * @return
     */
    public static User currentUser() {
        HttpSession httpSession = Tools.currentSession();
        if (httpSession == null) {
            return null;
        }
        User user = (User) Tools.currentSession().getAttribute(CommonConstant.PRINCIPAL);
        return user;
    }


    /**
     * 当前用户id
     * 先从当前线程获取，再从session中获取，最后从sa-token中获取
     *
     * @return
     */
    public static Integer currentUserId() {
        User user = getUserFromInheritableLocal();
        if (user != null) {
            return user.getId();
        }
        user = currentUser();

        if (user != null) {
            return user.getId();
        }
        try {
            return StpUtil.getLoginIdAsInt();
        } catch (Exception e) {
//            LOGGER.warn("从sa-token获取当前用户id失败");
            return null;
        }
    }

    public static boolean isLoginUser(Integer userId) {
        return NumberUtils.equals(currentUserId(), userId);
    }

    /**
     * 当前登录用户是否是管理员
     *
     * @return whether admin
     */
    public static boolean isAdmin() {
        User user = currentUser();
        if (user == null) {
            return false;
        }
        return user.isAdmin();
    }

    /**
     * 是否可以编辑数据：当前用户自己创建的 或者当前用户是admin
     *
     * @param userId 数据的创建人id
     * @return could edit
     */
    public static boolean couldEdit(Integer userId) {
        return isAdmin() || isLoginUser(userId);
    }


}
